package com.xinchao.job.task;

import java.io.Serializable;
import java.util.List;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.xinchao.common.model.JobEvent;
import com.xinchao.job.JobManager;
import com.xinchao.job.service.JobEventService;


/**
 * 
 * <p>Title: InitJob</p>  
 * <p>Description: 维护job任务调度的job(如动态更改job执行时间)</p>  
 * @author huangf 
 * @date 2018年5月15日
 */
@DisallowConcurrentExecution
public class CheckJob implements  Job,Serializable{
	private static final long serialVersionUID = 1L;
	/**
	 * 
	 */
	private static Logger logger = LoggerFactory.getLogger(CheckJob.class);
	@Autowired
	private JobEventService jobService;
	@Autowired 
	private JobManager jobManager;

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		logger.info("执行【CheckJob】" );
		List<JobEvent> listJobEvent = jobService.listJobEvent();
		for ( JobEvent event : listJobEvent ) {
			if ( !Boolean.TRUE.equals(event.getState()) ) {
				// 移除job
				jobManager.removeJob(event.getJobName(), event.getJobGroup(), event.getJobName(), event.getJobGroup());
				continue;
			} else {
				// 新增或修改job
				jobManager.addOrUpdateJob(event.getJobName(), event.getJobGroup(), event.getJobName() + "-trigger", event.getJobGroup(),event.getJobClassName(),event.getCronExpression());
			}
		}
	}
	
}